﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using ServeurRSS_1_0.Source.Model;
using ServeurRSS_1_0.Source.ExceptionRss;

namespace ServeurRSS_1_0.Services
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "RssService" in code, svc and config file together.
    [AspNetCompatibilityRequirements(
                  RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RssService : IServiceRssManagement
    {

        private RssModel modelRss
        { get; set; }

        public RssService()
        { 
            modelRss = new RssModel();
        }

        public string addExistingRssToDirectory(System.Guid dir, System.Guid rss)
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                if (db.DirectoriesRsses.FirstOrDefault<DirectoriesRss>(p => p.fk_id_Directories == dir && p.fk_id_Rss == rss) != null)
                    return "Already add in this directory";

                DirectoriesRss rssLink = new DirectoriesRss();
                rssLink.id = Guid.NewGuid();
                rssLink.fk_id_Directories = dir;
                rssLink.fk_id_Rss = rss;
                db.DirectoriesRsses.InsertOnSubmit(rssLink);
                db.SubmitChanges();
                string res = modelRss.addRssToUserWithDir(dir, rss, false);
                return res;
            }
            catch (ExceptionUpdate e)
            {
               return ("NOK " + e.Message);
            }
        }

        public string createRssForUser(System.Guid user, string nameRss, System.Guid idDirectory)
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                Rss userRss = new Rss
                {
                    id = Guid.NewGuid(),
                    last_date_importation = DateTime.Now,
                    name = nameRss,
                    url = ""
                };
              
                modelRss.addRssToUser(user, userRss.id, true);
                db.Rsses.InsertOnSubmit(userRss);
                db.SubmitChanges();
                addExistingRssToDirectory(idDirectory, userRss.id);
            }
            catch (Exception e)
            {
                return "NOK " + e.Message;
            }
            return "OK";
        }


        public string addNewRssToDirectory(System.Guid dir, string urlRss)
        {
            string res = "";
            System.Guid? idRss = null;
            try
            {
                if ((idRss = modelRss.checkUrlRss(urlRss)) == null)
                {
                    idRss =(Guid?) System.Guid.NewGuid();
                    modelRss.integrateRss(idRss, urlRss, false);
                }
                //        modelRss.checkFeed = modelRss.checkFeedIntegrate;
                else
                    modelRss.integrateRss((System.Guid)idRss, urlRss, true);
                        
                    //        modelRss.checkFeed = modelRss.checkFeedUpdate;
            //    if (idRss == null)
            //        idRss = Guid.NewGuid();
            //   res = modelRss.integrateRss((System.Guid)idRss, urlRss);
                modelRss.insertionEnded += (obj, arg) => { this.addExistingRssToDirectory(dir, (System.Guid)idRss);};


            }
            catch (ExceptionUpdate e)
            {
                res += "NOK for update " + e.Message;
            }
            catch (Exception e)
            {
                return "Erreur Integration Item " + e.Message;
            }
            return res;
        }


        public string addListRssToDirectory(List<System.Guid> listIdRss, List<string> listUrlRss, System.Guid dir)
        {
            int i = 0;
            string res = "";
            foreach (System.Guid idRss in listIdRss)
            {
                res += "\r\n" + i.ToString() + " --> ";
                res += addExistingRssToDirectory(dir, idRss);
            }
            foreach (string url in listUrlRss)
            {
                res += i.ToString() + " --> ";
                res += addNewRssToDirectory(dir, url);
            }
            return res;
        }

        public string eraseListRssFromDirectory(Guid dir,Guid userId, List<Guid> listId)
        {
            string rep = "";
            foreach (Guid tmp in listId)
                rep += eraseRssFromDirectory(dir, userId, tmp);
            return rep;
        }

        public string eraseRssFromDirectory(System.Guid dir, Guid UserId, System.Guid rss)
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();

                DirectoriesRss erase = db.DirectoriesRsses.SingleOrDefault(p => p.fk_id_Rss == rss && p.fk_id_Directories == dir);
                db.DirectoriesRsses.DeleteOnSubmit(erase);

                UserRss rssErase = db.UserRsses.SingleOrDefault(p => p.fk_id_Rss == rss && p.fk_id_User == UserId);
                db.UserRsses.DeleteOnSubmit(rssErase);

                db.SubmitChanges();
                return "OK";
            }
            catch (Exception e)
            {
                return "NOK " + e.Message; 
            }
        }

        public string moveRss(System.Guid oldId, System.Guid newId, System.Guid rssID)
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                DirectoriesRss current = db.DirectoriesRsses.Single(d => d.fk_id_Rss == rssID && d.fk_id_Directories == oldId );
                if (newId == System.Guid.Empty)
                    current.fk_id_Directories = null;
                else
                    current.fk_id_Directories = newId;
                db.SubmitChanges();
                return "OK";
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public List<DataRss> getRssForDirectory(System.Guid dir)
        {
            try
            {
                List<Rss> list = modelRss.getRssForDir(dir);
                return modelRss.getListDataRss(list);
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public List<DataRss> getAllRssForUser(System.Guid idUser, bool? owner = null)
        {
            try
            {
                return modelRss.getListDataRss(modelRss.getRssUser(idUser, owner));
            }
            catch (Exception e)
            {
                return null;
            }
        }


        public RssTree getAllHierarchicalRssForUser(System.Guid idUser)
        {
            try
            {
                RssTree list = modelRss.getUserFullTree(idUser);
                return list;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public List<DataRss> getAllRss()
        {
            try
            {
                List<Rss> list = modelRss.getAllRssAvailable();
                return modelRss.getListDataRss(list);
            }
            catch (Exception e)
            {
                return null;
            }
        }


        public List<DataItem> getListItemForRss(System.Guid rss, int limit = 20, int page = 1)
        {
            try
            {
                    modelRss.integrateRss(rss, "", true);
            }
            catch (Exception e)
            {
                Console.WriteLine("Erreur GetListItem  " + e.Message);
            }
            try
            {
                ItemModel tmpModel = new ItemModel();
                List<DataItem>  list = tmpModel.getItems(rss, limit, page);
                return list;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public bool setReadedItem(List<System.Guid> listItemsRead, Guid idUser)
        {
            if (listItemsRead == null || listItemsRead.Count <= 0 || idUser == null || idUser == Guid.Empty)
                return false;
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                List<UserItem> listRes = new List<UserItem>();
                foreach (Guid idItem in listItemsRead)
                {
                    UserItem userReadItem = new UserItem 
                    {
                        fk_id_Items = idItem != null ? idItem : Guid.Empty,
                        fk_id_User = idUser,
                        isRead = true,
                        id = Guid.NewGuid()
                    };

                    listRes.Add(userReadItem);
                }
                if (listRes.Count > 0)
                    db.UserItems.InsertAllOnSubmit(listRes);
                db.SubmitChanges();
                return true;
            }
            catch
            {
            return false;
            }

        }
    }
}
